package it.ap.sa.core.httpclient;

import java.util.Iterator;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;

import it.ap.sa.core.utils.costants.SecurityConstants;

/**
 * @author Alessandro Paolillo
 */
class CookieBean {

	private CookieStore cookieStore = null;
	private HttpContext httpContext = null;
	private String      xsrfToken   = null;
	private long        timestamp   = 0L;
	
	public CookieBean(CookieStore cookieStore, HttpContext httpContext) {
		super();
		this.cookieStore = cookieStore;
		this.httpContext = httpContext;
		this.aggiornaTimestamp();
		this.valorizzaToken   ();
	}
	/**
	 * @author Alessandro Paolillo
	 */
	private void valorizzaToken(){
		if(this.cookieStore.getCookies() != null){
			String  cookieName = SecurityConstants.CSRF_COOKIE_NAME.value();
			boolean trovato    = false;
			for(Iterator<Cookie> iterator = this.cookieStore.getCookies().iterator(); iterator.hasNext() && trovato == false ; ){
				Cookie cookie = iterator.next();
				if(cookie.getName().equals(cookieName)){
					trovato = true;
					this.xsrfToken = cookie.getValue();
				}
			}
		}		
	}
	/**
	 * @author Alessandro Paolillo
	 */
	public boolean isValid(){
		return System.currentTimeMillis() - this.timestamp < 1800000;
//		return false;
	}

	public void aggiornaTimestamp(){
		this.timestamp = System.currentTimeMillis();
	}
	
	/**
	 * @return the cookieStore
	 */
	public CookieStore getCookieStore() {
		return cookieStore;
	}

	/**
	 * @return the httpContext
	 */
	public HttpContext getHttpContext() {
		return httpContext;
	}

	/**
	 * @return the xsrfToken
	 */
	public String getXsrfToken() {
		return xsrfToken;
	}
}
